﻿Imports EyeOpen.Diagnostics
Imports System.Linq

Namespace EyeOpen.ShellCommand.Windows

	Partial Public Class MainForm
		Inherits Form
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub ExecuteLinkLabelLinkClicked(ByVal sender As Object, ByVal e As LinkLabelLinkClickedEventArgs) Handles executeLinkLabel.LinkClicked
			outputTextBox.Clear()

			Dim commandList = commandsTextBox.Text.Split(vbCrLf.ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(AddressOf ParamterFromLine).ToArray()

			Dim shellProcess = New ShellProcess

			Dim readLineFunction = Function(line As String) outputTextBox.Invoke(Sub() outputTextBox.Text = outputTextBox.Text & line & Environment.NewLine)

			Dim endLineFunction = Sub()
									  outputTextBox.Invoke(Sub()
															   outputTextBox.SelectionStart = outputTextBox.Text.Length
															   outputTextBox.ScrollToCaret()
														   End Sub)
								  End Sub

			shellProcess.Execute(readLineFunction, endLineFunction, commandList)
		End Sub

		Private Function ParamterFromLine(ByVal line As String) As Diagnostics.ShellCommand
			Dim spaceIndex = line.IndexOf(" "c)

			Dim command = If(spaceIndex = -1, New Diagnostics.ShellCommand(line), New Diagnostics.ShellCommand(line.Substring(0, spaceIndex), line.Substring(spaceIndex + 1)))

			Return command
		End Function
	End Class
End Namespace
